package com.flyme.gateway.provider.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.flyme.common.core.constants.ResultEnum;
import com.flyme.common.core.model.ResultBody;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 无效token 异常重写
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Map<String, Object> map = new HashMap<>();
        Throwable cause = authException.getCause();
        ResultBody resultBody;
        if (cause instanceof InvalidTokenException) {
            resultBody= ResultBody.failed(ResultEnum.INVALID_TOKEN,"凭证已失效,请重新登录");
        } else {
            resultBody= ResultBody.failed(ResultEnum.INVALID_TOKEN,"访问此资源需要完全的身份验证");
        }
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(),resultBody );
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}
